<?php

/**
 * 
 * @author Nguyen Van Nhieu <nhieunv@evolable.asia>
 * Mar 27, 2013
 * File: comment_controller.php
 *
 **/ 
class CommentsController extends AppController {
	var $uses = array('Comment');
	var $limit = 3;
	public function beforeFilter() {
		parent::beforeFilter();
		$this->CustomAuth->allow('index', 'listOfElement', 'itemAjax','addReply');
	}
	function index($courseId){
		if(!empty($this->data)){
			$commentId = $this->data['commentId'];
			$result = $this->Comment->deleteCommentById($commentId, $this->CustomAuth->user('id'));
		}
		$this->loadModel('Course');

		$userId = 0;
		if ($user = $this->CustomAuth->user()) {
			$userId = $user['User']['id'];
		}

		if (!$this->Session->check('Admin.isLogin') || !$this->Session->read('Admin.isLogin')) {
			$options['conditions'] = array(
				$this->Course->alias . '.del_flg' => 0,
				'OR' => array(
					$this->Course->alias . '.display_flg' => 1,
					$this->Course->alias . '.user_id' => $userId,
				)
			);
		}
		$options['conditions'][$this->Course->alias . '.' . $this->Course->primaryKey] = $courseId;

		$course = $this->Course->getForView($options);

		if (!$course) {
			$this->cakeError('error404');
		}
		if (isset($this->params['url']['detail']) && $detailId = $this->params['url']['detail']) {
			$detail = $this->Course->getCourseDetail($courseId, $detailId);
		}
		if (!isset($detail) || !$detail) {
			$details = $this->Course->getClosestCourseDetail($courseId);
			$detail = array();
			if (isset($details[$courseId])) {
				$detail = $details[$courseId];
			}
		}
		$this->loadModel('CourseDetail');
		//check if joined to a course detail
		$this->loadModel('EnteredCourse');
		$this->loadModel('TargetOfWatch');
		$isJoined = false;
		$isFull = false;
		if ($detail) {
			$isJoined = $this->EnteredCourse->isEnteredCourse($detail['CourseDetail']['id'], $userId);
			$isFull = $this->CourseDetail->isFull($detail['CourseDetail']['id']);
		}

		$exclusiveIds = array($course['Course']['id']);

		$userCourses = $this->Course->getRelatedByUser($course['Course']['user_id'], $exclusiveIds);

		$exclusiveIds = array_merge($exclusiveIds, array_keys($userCourses));
		$categoryCourses = $this->Course->getRelatedByCategory($course['Course']['category'], $exclusiveIds);

		$exclusiveIds = array_merge($exclusiveIds, array_keys($categoryCourses));
		$areaCourses = $this->Course->getRelatedByArea($course['Course']['area'], $exclusiveIds);

		$this->loadModel('Tag');
		$watchListInfo = $this->TargetOfWatch->getTargetOfWatchInformationByUserIdAndTeacherId($this->CustomAuth->user('id'), $course['Course']['user_id']);
		$this->set(array(
			'course' => $course,
			'detail' => $detail,
			'areaCourses' => $areaCourses,
			'tags' => $this->Tag->getTagByCourse($courseId),
			'categoryCourses' => $categoryCourses,
			'userCourses' => $userCourses,
			'isJoined' => $isJoined,
			'isFull' => $isFull,
			'watchListInfo' => $watchListInfo,
		));
		
		$options = $this->Comment->getPagingOption(NULL, NULL);
		$options['conditions'] = array(
			'Comment.comment_id = 0',
			'Comment.del_flg = 0',
			'Comment.course_id' => $courseId,
			);
		$this->paginate = $options;
		$comments = $this->paginate('Comment');
		if(is_array($comments)){
			foreach ($comments as $key => $commnet) {
				$replies = $this->Comment->getReplyByCommnentId($commnet['Comment']['id'], $this->limit, array('Comment.created' => 'DESC'));
				krsort($replies);
				$comments[$key]['Reply'] = $replies;
			}
		}
		$this->set(array(
			'comments' => $comments, 
			'courseId' => $courseId,
			'showPostForm' => false, 
			'showAll' => 0,
			'userId' => $this->CustomAuth->user('id')
		));
	}
	
	function listOfElement($courseId) {
		if(!isset($courseId)){
			$this->cakeError('error404');
		}
		if(isset($this->params['requested'])){
			$comments = $this->_prepareData($courseId);
			// return comments, show pagination
			return array($comments, true, $this->CustomAuth->user('id'), 0);
		}
	}
	
	function itemAjax(){
		if (!$this->RequestHandler->isAjax()) {
			$this->cakeError('error404');
		}
		$this->loadModel('Comment');
		$courseId = '';
		$commentId = '';
		if(isset($this->params['url']['courseId'])){
			$courseId = $this->params['url']['courseId'];
		}
		if(isset($this->params['url']['commentId'])){
			$commentId = $this->params['url']['commentId'];
		}
		$comment = $this->Comment->getReplyByCommentIdAndCourseId($commentId, $courseId, NULL, array('Comment.created' => 'ASC'));
		$result = $this->Comment->getCommentById(array('total_reply'), $commentId);
		if(count($result) > 0){
			$replyNumber = $result['Comment']['total_reply'];
		}else{
			$replyNumber = 0;
		}
		$this->set(array(
			'comment' => $comment,
			'replyNumber' => $replyNumber,
			'showPostForm' => true,
			'userId' => $this->CustomAuth->user('id'),
			'commentId' => $commentId,
			'showAll' => 1
		));
		return $this->render('/elements/comment/reply_item', 'ajax');
	}
	
	function add(){
		if (!$this->RequestHandler->isAjax()) {
			$this->cakeError('error404');
		}
		if(isset($_POST['courseId']) && isset($_POST['content'])){
			$userId = $this->CustomAuth->user('id');
			//if user not yet to login
			if(!$userId){
				$url = Router::url(array('controller' => 'Users', 'action' => 'signin'));
				$this->set(array(
					'url' => $url
				));
				//redirect url after login
				$this->Session->write('Auth.redirect', $this->referer());
				return $this->render('/elements/blank_page', 'ajax');
			}
			$this->loadModel('Comment');
			$this->loadModel('Course');
			$courseId = $_POST['courseId'];
			if($this->Course->isOwner($courseId, $userId)){
				$userType = Comment::OWNER_TYPE;
			}elseif($this->Course->isJoined($courseId, $userId)){
				$userType = Comment::JOINED_TYPE;
			}else{
				$userType = Comment::NORMAL_TYPE;
			}
			if(intval($courseId) > 0){
				$content = trim(htmlspecialchars($_POST['content']));
				$data = array(
					'course_id' => $courseId,
					'user_id' => $this->CustomAuth->user('id'),
					'content' => $content,
					'comment_id' => 0,
					'total_reply' => 0,
					'del_flg' => 0,
					'user_type' => $userType,
					'created' => date('Y-m-d H:i:s'),
					'modified' => date('Y-m-d H:i:s')
					
				);
				if($this->Comment->save($data)){
					$comments = $this->_prepareData($courseId);
					$this->set(array(
						'comments' => $comments,
						'userId' => $userId,
						'showPostForm' => true,
						'showAll' => $this->_showAll()
					));
					
				}else{
					$comments = $this->_prepareData($courseId);
					$this->set(array(
						'comments' => $comments,
						'userId' => $userId,
						'showPostForm' => true,
						'showAll' => $this->_showAll(),
						'errorMessage' => Messages::there_some_problem_please_try_later
					));
				}
			}
		}else{
			$comments = $this->_prepareData($courseId);
			$this->set(array(
				'comments' => $comments,
				'userId' => $userId,
				'errorMessage' => Messages::there_some_problem_please_try_later,
				'showPostForm' => true,
				'showAll' => $this->_showAll()
			));
		}
		return $this->render('/elements/comment/list_comment_ajax', 'ajax');
	}
	
	function addReply(){
		if (!$this->RequestHandler->isAjax()) {
			$this->cakeError('error404');
		}
		if(isset($this->data)){
			$userId = $this->CustomAuth->user('id');
			$this->loadModel('Comment');
			$this->loadModel('Course');
			$courseId = $this->data['courseId'];
			$commentId = $this->data['commentId'];
			if(intval($courseId) > 0){
				if($this->Course->isOwner($courseId, $userId)){
				$userType = Comment::OWNER_TYPE;
				}elseif($this->Course->isJoined($courseId, $userId)){
					$userType = Comment::JOINED_TYPE;
				}else{
					$userType = Comment::NORMAL_TYPE;
				}
				$content = trim(htmlspecialchars($this->data['content']));
				if($content == ''){
					return $this->_errorReturn(Messages::you_must_enter_the_content_of_comment);
				}
				$data = array(
					'course_id' => $courseId,
					'user_id' => $this->CustomAuth->user('id'),
					'content' => $content,
					'comment_id' => $commentId,
					'total_reply' => 0,
					'del_flg' => 0,
					'user_type' => $userType,
					'created' => date('Y-m-d H:i:s'),
					'modified' => date('Y-m-d H:i:s')
					
				);
				if($this->Comment->saveComment($data)){
					$reply = $this->Comment->getCommentById(NULL, $this->Comment->id);
					$this->set(array(
						'reply' => $reply,
						'userId' => $userId,
						'showAll' => $this->_showAll()
					));
					$content = $this->render('/elements/comment/reply_post', 'ajax');
					$commentResult = $this->Comment->find('first', array(
						'conditions' => array(
							'Comment.id' => $commentId
						)
					));
					$total = 0;
					if(count($commentResult) > 0){
						$total = $commentResult['Comment']['total_reply'];
					}
					$result = array(
						'status' => true,
						'data' => $content,
						'total' => 'comment('.$total.')'
					);
					$this->output = ''; 
					$this->set(array('json' => $result));
					return $this->render('/elements/json', 'ajax');
				}else{
					return $this->_errorReturn(Messages::there_some_problem_please_try_later);
				}
			}else{
				return $this->_errorReturn(Messages::there_some_problem_please_try_later);
			}
		}else{
			return $this->_errorReturn(Messages::there_some_problem_please_try_later);
		}
	}
	
	function deleteReply(){
		if (!$this->RequestHandler->isAjax()) {
			$this->cakeError('error404');
		}
		if(isset($this->data)){
			$userId = $this->CustomAuth->user('id');
			$this->loadModel('Comment');
			$this->loadModel('Course');
			$commentId = $this->data['commentId'];
			if(isset($this->data['showAll']) && $this->data['showAll'] == 1){
				$limit = 0;
				$order = array('Comment.created' => 'ASC');
			}else{
				$limit = $this->limit;
				$order = array('Comment.created' => 'DESC');
			}
			$parentId = '';
			$result = $this->Comment->deleteReplyById($commentId, $userId, $parentId);
			if($result == 1){
				$comment = $this->Comment->getReplyByCommentId($parentId, $limit, $order);
				$result = $this->Comment->find('first', array(
					'conditions' => array(
						'Comment.id' => $parentId
					)
				));
				if(count($result) > 0){
					$replyNumber = $result['Comment']['total_reply'];
				}else{
					$replyNumber = 0;
				}
				$this->set(array(
					'comment' => $comment,
					'replyNumber' => $replyNumber,
					'showPostForm' => true,
					'commentId' => $parentId,
					'userId' => $this->CustomAuth->user('id'),
					'showAll' => $this->_showAll()
				));
				$content = $this->render('/elements/comment/reply_item', 'ajax');
				$this->output ='';
				$ajaxResult = array(
					'status' => true,
					'commentId' => $parentId,
					'total' => 'comments('.$replyNumber.')',
					'message' => Messages::successfully,
					'data' => $content,
				);
				$this->set(array(
					'json' => $ajaxResult
				));
				return $this->render('/elements/json', 'ajax');
			}elseif ($result == 0) {
				return $this->_errorReturn(Messages::you_could_not_delete_this_comment);
			}else{
				return $this->_errorReturn(Messages::there_some_problem_please_try_later);
			}
		}else{
			return $this->_errorReturn(Messages::there_some_problem_please_try_later);
		}
	}
	
	function delete(){
		if (!$this->RequestHandler->isAjax()) {
			$this->cakeError('error404');
		}
		if(isset($this->data)){
			$userId = $this->CustomAuth->user('id');
			$this->loadModel('Comment');
			$this->loadModel('Course');
			$commentId = $this->data['commentId'];
			$courseId = $this->data['courseId'];
			$result = $this->Comment->deleteCommentById($commentId, $userId);
			if($result == 1){
				$comments = $this->_prepareData($courseId);
					$this->set(array(
						'comments' => $comments,
						'userId' => $userId,
						'showPostForm' => true,
						'showAll' => $this->_showAll()
					));
				$content = $this->render('/elements/comment/list_comment_ajax', 'ajax');
				$this->output ='';
				$ajaxResult = array(
					'status' => true,
					'message' => Messages::successfully,
					'data' => $content,
				);
				$this->set(array(
					'json' => $ajaxResult
				));
				return $this->render('/elements/json', 'ajax');
			}elseif ($result == 0) {
				return $this->_errorReturn(Messages::you_could_not_delete_this_comment);
			}else{
				return $this->_errorReturn(Messages::there_some_problem_please_try_later);
			}
		}else{
			return $this->_errorReturn(Messages::there_some_problem_please_try_later);
		}
	}
	
	function _showAll(){
		if(isset($this->data['showAll'])){
			$showAll = $this->data['showAll'];
		}else{
			$showAll = 0;
		}
		return $showAll;
	}
	function _errorReturn($message){
		$result = array(
			'status' => false,
			'data' => $message
		);
		$this->set(array('json' => $result));
		return $this->render('/elements/json', 'ajax');
	}
	function _prepareData($courseId){
		$this->loadModel('Comment');
		$comments = $this->Comment->getCommentsByCourseId($courseId,  $this->limit, array('Comment.created' => 'DESC'));
		if(is_array($comments)){
			foreach ($comments as $key => $commnet) {
				$replies = $this->Comment->getReplyByCommnentId($commnet['Comment']['id'], $this->limit, array('Comment.created' => 'DESC'));
				krsort($replies);
				$comments[$key]['Reply'] = $replies;
			}
		}
		return $comments;
	}
	
}